//TEH HEADERZ LAWL
//Shared includes,defines or functions go here
#include <stdio.h>
#include <Iostream>
#include <conio.h>
#include <windows.h>
#include <string>
#include <vector>
#include <shellapi.h>
#include "Controller.h"
using namespace std;

void Pause(void)
{
	int Button;
	cout << "\nPress any key to continue...\n";
	while(1)
	{
		if(_kbhit())
		{
			Button = _getch();
			if (Button != NULL)
				break;
		}
	}
}
Controller LoadSettings(void)
{
	Controller Pad;
	FILE * SettingsFile;
	if((SettingsFile = fopen ("Settings","rb")) == NULL)
	{
		cout << "Could not load settings, trying to remake file & use defaults...\n";
		if((SettingsFile = fopen ("Settings","wb")) == NULL)
		{
			cout << "\nCould Not create Settings file!!!\nCould Not use default settings!!!\n\n";
			cout << "program will exit\n";
			Pause();
			exit(1);
		}
		else
		{
			//TODO: complete the Dpad part once the Dpad is "emulated" better and add C stick once
			//i know the C stick value's and everything
			//default settings writing&assignment here
			fprintf(SettingsFile,"B013115113122100097101114\nA111108107109105112059058\nD116103102104");
			Pad.SetButtons(13,115,113,122,100,97,101,114);
			Pad.SetAnalog(111,108,107,109,105,112,58,59);
			Pad.SetDigital(116,103,102,104);
		}
	}
	else
	{
		char Buffer[32];
		char temp[32];
		int A1 = 0;
		int A2 = 0;
		int A3 = 0;
		int A4 = 0;
		int A5 = 0;
		int A6 = 0;
		int A7 = 0;
		int A8 = 0;
		while (fgets(Buffer,256,SettingsFile) !=NULL)
		{
			strncpy(temp,"",32);
			switch(Buffer[0])
			{
			case 'B':
				sscanf( &Buffer[1], "%3u%3u%3u%3u%3u%3u%3u%3u", &A1, &A2, &A3, &A4, &A5, &A6, &A7, &A8 );
				Pad.SetButtons(A1,A2,A3,A4,A5,A6,A7,A8);
				break;
			case 'A':
				sscanf( &Buffer[1], "%3u%3u%3u%3u%3u%3u%3u%3u", &A1, &A2, &A3, &A4, &A5, &A6, &A7, &A8 );
				Pad.SetAnalog(A1,A2,A3,A4,A5,A6,A7,A8);
				break;
			case 'D':
				sscanf( &Buffer[1], "%3u%3u%3u%3u%3u%3u%3u%3u", &A1, &A2, &A3, &A4, &A5, &A6, &A7, &A8 );
				//can only be used once i add more ways for the digital pad
				Pad.SetDigital(A1,A2,A3,A4);//,A5,A6,A7,A8);
				break;
			default:
				Pad.SetButtons(13,115,113,122,100,97,101,114);
				Pad.SetAnalog(111,108,107,109,105,112,58,59);
				Pad.SetDigital(116,103,102,104);
				cout << "\nInvalid Settings File!!!\nUsing default Settings....\n";
			}
		}
	}
	return Pad;
}